package com.study;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mayjean
 * @Date2020/10/8
 */
public class ManagerFactory {


    private static Map<String,LoadInfo> loadInfoMap = new HashMap();

    public static final String CLASS_PATH = "D:\\IdeaProjects\\classloader-demo\\target\\classes\\";

    public static final String MY_MANAGER = DefaultBaseManager.class.getName();

    public static BaseManager getManager(String className){
        File file = new File(CLASS_PATH+""+className.replace(".","/")+".class");
        long lastModified = file.lastModified();
        if (loadInfoMap.get(className) == null) {
            load(className,lastModified);
        }
        else if(loadInfoMap.get(className).getLoadTime() != lastModified){
            load(className,lastModified);
        }
        return loadInfoMap.get(className).getBaseManager();
    }

    private static void load(String className,long lastModified) {
        MyClassLoader myClassLoader = new MyClassLoader(CLASS_PATH);
        Class<?> loadClass = null;
        try {
            loadClass = myClassLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        BaseManager manager = newInstance(loadClass);
        LoadInfo loadInfo = new LoadInfo(myClassLoader,lastModified);
        loadInfo.setBaseManager(manager);
        loadInfoMap.put(className,loadInfo);
        return;
    }

    private static BaseManager newInstance(Class<?> loadClass) {
        try {
            return (BaseManager)loadClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }


}